import { useEffect } from "react";
import { Popconfirm, Pagination, Avatar, message, Row, Col, Tag, Alert, Radio, Modal } from "antd";
import { Button, ButtonGroup, Card as SemiCard, List } from "@douyinfe/semi-ui";
import { IconPlusCircle, IconRefresh, IconDelete } from "@douyinfe/semi-icons";
import { useReactive } from "ahooks";
import { useModel } from "umi";
import Jdenticon from "react-jdenticon";
import { AllRoleMembers, AllApplications, DeleteRoleMember, FindRole, UpdateReviewType, CreateOrgRole } from "../_graphql/approles";
import SetRoleMembers from "../_modals/approles/set.members";
import SetLevelModal from "../_modals/approles/set.level";

export default function ApplicationRolesPage() {
    const { windowInnerHeight, graphqlFetch } = useModel("global");
    const { kuboUrl } = useModel("kubo");
    const { setModalVisible, setModalTitle, setModalComponent, setModalStyle, setModalWidth } = useModel("global.modal");
    const { remoteOrganizationInfo } = useModel("organization.info");

    const state = useReactive({
        loading: false,
        memberLoading: false,
        roleMembers: [],
        roleGroupMembers: [],
        applications: [],
        selectedApplication: {},
        roleLoading: false,
        roles: [],
        selectedRole: null,
        totalCount: 0,
        pageSize: 20,
        page: 1,
        orgRole: {}, //组织内查询出来的应用角色信息
    });

    const loadApplications = async () => {
        state.loading = true;
        state.roles = [];
        let res = await graphqlFetch({
            query: AllApplications,
            variables: {
                first: state.pageSize || 20,
                offset: (state.page - 1) * state.pageSize || 0,
            },
        });
        state.applications = res?.a?.nodes || [];
        state.totalCount = res?.a?.totalCount || 0;
        state.selectedApplication = res?.a?.nodes?.length > 0 ? res.a.nodes[0] : {};
        state.loading = false;
    };

    useEffect(() => {
        loadApplications();
    }, []);

    const loadApplicatinRoles = async () => {
        state.roleLoading = true;
        state.selectedRole = null;
        state.roles = [];
        try {
            const { aiUuid, aiName, b } = state.selectedApplication;
            let data = { aiUuid, aiName };
            if (b?.nodes?.length) data = { ...data, ...b.nodes[0] };
            if (data.atHash) {
                let response = await fetch(kuboUrl + data.atHash + "/reviewer_roles.json", {
                    cache: "no-cache",
                });
                let roles = await response.json();

                let res = await graphqlFetch({
                    query: FindRole,
                    variables: {
                        aiUuid: state.selectedApplication.aiUuid,
                        arName: state.selectedRole,
                    },
                });
                state.orgRole = res?.a?.nodes || [];

                if (state.orgRole?.length > 0) {
                    Object.keys(roles).map((key) => {
                        if (state.orgRole.find((item) => item.arName === key)?.arType) {
                            roles[key].type = state.orgRole.find((item) => item.arName === key).arType;
                            roles[key].level = state.orgRole.find((item) => item.arName === key).arLeve;
                        }
                    });
                }
                state.roles = roles;

                let keys = Object.keys(state.roles);
                keys.length > 0 && (state.selectedRole = keys[0]);
            }
        } catch (error) {}
        state.roleLoading = false;
    };

    useEffect(() => {
        state.selectedApplication?.aiUuid && loadApplicatinRoles();
    }, [state.selectedApplication]);

    const loadRoleMembers = async () => {
        state.memberLoading = true;
        if (state.selectedApplication?.aiUuid && state.selectedRole) {
            let res = await graphqlFetch({
                query: AllRoleMembers,
                variables: {
                    aiUuid: state.selectedApplication.aiUuid,
                    arName: state.selectedRole,
                },
            });
            state.roleMembers = res?.a?.nodes || [];
            state.roleGroupMembers = res?.a?.nodes ? helper.transGroup(res.a.nodes, "arLeve", "arLeve") : [];
        }
        state.memberLoading = false;
    };

    useEffect(() => {
        loadRoleMembers();
    }, [state.selectedApplication, state.selectedRole]);

    const openRoleSetMembers = () => {
        setModalTitle("设置应用角色成员");
        setModalStyle({ top: 100 });
        setModalWidth(700);
        setModalComponent(
            <SetRoleMembers
                application={state.selectedApplication}
                roleKey={state.selectedRole}
                role={state.roles[state.selectedRole]}
                roleMembers={state.roleMembers}
                reloadData={loadRoleMembers}
                reloadRole={(neworgRole) => {
                    state.orgRole = [...state.orgRole, neworgRole];
                }}
            />
        );
        setModalVisible(true);
    };

    const openSetLevelModal = () => {
        setModalTitle("设置审核层级");
        setModalStyle({ top: 100 });
        setModalWidth(500);
        setModalComponent(
            <SetLevelModal
                application={state.selectedApplication}
                roleKey={state.selectedRole}
                role={state.roles[state.selectedRole]}
                reloadData={(level, neworgRole) => {
                    state.roles[state.selectedRole].level = level;
                    if (neworgRole) state.orgRole = [...state.orgRole, neworgRole];
                }}
            />
        );
        setModalVisible(true);
    };

    const deleteRoleMember = async (omUuid) => {
        let res = await graphqlFetch({
            query: DeleteRoleMember,
            variables: {
                aiUuid: state.selectedApplication.aiUuid,
                arName: state.selectedRole,
                omUuid,
            },
        });
        if (res) {
            message.success("成功移除应用角色成员信息");
            loadRoleMembers();
        }
    };

    const changeReviewType = async (item, value) => {
        if (!remoteOrganizationInfo.isOpenExamine && value === "审核") {
            Modal.confirm({
                content: "组织未开通审核功能无法切换！",
            });
        } else if (!remoteOrganizationInfo.isOpenApprove && value === "审批") {
            Modal.confirm({
                content: "组织未开通审批功能无法切换！",
            });
        } else {
            Modal.confirm({
                content: "确认切换（审核⇄审批）方式为" + value + "吗？",
                onOk: async () => {
                    if (state.orgRole.findIndex((item) => item.aiUuid === state.selectedApplication.aiUuid && item.arName === state.selectedRole) !== -1) {
                        let res = await graphqlFetch({
                            query: UpdateReviewType,
                            variables: {
                                aiUuid: state.selectedApplication.aiUuid,
                                arName: state.selectedRole,
                                arType: value,
                            },
                        });
                        if (res) {
                            message.success("成功切换为" + value + "方式");
                            state.roles[state.selectedRole].type = value;
                        }
                    } else {
                        let variables = {
                            aiUuid: state.selectedApplication.aiUuid,
                            arName: state.selectedRole,
                            arCrti: new Date().getUTCTime(),
                            arUpti: new Date().getUTCTime(),
                            arLeve: item.level,
                            arRemk: item.levelText,
                            arType: value,
                        };
                        let res = await graphqlFetch({
                            query: CreateOrgRole,
                            variables,
                        });
                        if (res) {
                            message.success("成功切换为" + value + "方式");
                            state.roles[state.selectedRole].type = value;
                            state.orgRole = [...state.orgRole, variables];
                        }
                    }
                },
            });
        }
    };
    // 窗口头部：30，应用头：60，操作区内边距：24，卡面头：53，卡面脚：56，修正值：4
    const cardBodyHeight = windowInnerHeight - 90 - 48 - 53 - 4;

    return (
        <Row style={{ margin: 24 }} gutter={16}>
            <Col span={8}>
                <SemiCard
                    title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>应用列表</span>}
                    headerExtraContent={<Button theme="borderless" icon={<IconRefresh />} onClick={() => loadApplications()} />}
                    headerStyle={{ padding: "10px 14px" }}
                    shadows="always"
                    bordered={false}
                    bodyStyle={{ padding: 0, height: cardBodyHeight - 56 }}
                    footerStyle={{ padding: 0 }}
                    footerLine={true}
                    footer={
                        <div style={{ padding: 14, display: "flex", justifyContent: "space-between" }}>
                            <div></div>
                            <Pagination
                                total={state.totalCount}
                                showTotal={(total, range) => `当前显示第 ${range[0]}-${range[1]} 条，共 ${total} 条`}
                                pageSize={state.pageSize}
                                current={state.page}
                                showSizeChanger={false}
                                onChange={(page) => (state.page = page)}
                            />
                        </div>
                    }
                >
                    <List
                        loading={state.loading}
                        dataSource={state.applications}
                        style={{ padding: 10, height: cardBodyHeight - 56, overflow: "auto" }}
                        renderItem={(item, index) => (
                            <List.Item
                                key={index}
                                className={`list-item ${state.selectedApplication?.aiUuid === item?.aiUuid ? "list-item-selected" : ""}`}
                                header={<Avatar shape="square" src={<Jdenticon value={item.aiName || "-"} />} />}
                                main={
                                    <div>
                                        <div style={{ color: "var(--semi-color-text-0)", fontWeight: 500 }}>{item?.aiName || "-"}</div>
                                        {item?.aiDesc}
                                    </div>
                                }
                                onClick={() => (state.selectedApplication = item)}
                            ></List.Item>
                        )}
                    />
                </SemiCard>
            </Col>
            <Col span={8}>
                <SemiCard
                    title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>角色列表</span>}
                    headerExtraContent={<Button theme="borderless" icon={<IconRefresh />} onClick={() => loadApplicatinRoles()} />}
                    headerStyle={{ padding: "10px 14px" }}
                    shadows="always"
                    bordered={false}
                    bodyStyle={{ padding: 0, height: cardBodyHeight }}
                >
                    <List
                        loading={state.roleLoading}
                        dataSource={Object.keys(state.roles)}
                        renderItem={(key, index) => {
                            const item = state.roles[key];
                            let operator;
                            if (!remoteOrganizationInfo?.isOpenExamine && !remoteOrganizationInfo?.isOpenApprove)
                                operator = (
                                    <Button theme="borderless" disabled>
                                        未开启
                                    </Button>
                                );

                            if (remoteOrganizationInfo?.isOpenExamine || remoteOrganizationInfo?.isOpenApprove)
                                operator = (
                                    <Radio.Group
                                        options={[
                                            { label: "审核", value: "审核" },
                                            { label: "审批", value: "审批" },
                                            { label: "停用", value: "停用" },
                                        ]}
                                        onChange={(e) => changeReviewType(item, e.target.value)}
                                        value={item.type}
                                        optionType="button"
                                        buttonStyle="solid"
                                    />
                                );
                            return (
                                <List.Item
                                    key={index}
                                    extra={operator}
                                    className={`list-item ${state.selectedRole === key ? "list-item-selected" : ""}`}
                                    header={<Avatar shape="square" src={<Jdenticon value={item.label || "-"} />} />}
                                    main={
                                        <div>
                                            <div style={{ color: "var(--semi-color-text-0)", fontWeight: 500 }}>{item?.label + " " || " - "}</div>
                                            {item?.type === "审批" ? <Tag color="blue">{item?.type}</Tag> : <Tag color="blue">{item?.level + "级审核"}</Tag>}
                                        </div>
                                    }
                                    onClick={() => (state.selectedRole = key)}
                                ></List.Item>
                            );
                        }}
                    />
                </SemiCard>
            </Col>
            <Col span={8}>
                <SemiCard
                    title={
                        <span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>
                            {state.roles[state.selectedRole]?.type === "审批" ? "审批说明" : "成员列表"}
                        </span>
                    }
                    headerExtraContent={
                        <ButtonGroup size={"default"} theme="borderless">
                            <Button icon={<IconPlusCircle />} disabled={!state.selectedRole} onClick={openRoleSetMembers}></Button>
                            <Button icon={<IconRefresh />} onClick={loadRoleMembers}></Button>
                        </ButtonGroup>
                    }
                    headerStyle={{ padding: "10px 14px" }}
                    shadows="always"
                    bordered={false}
                    bodyStyle={{ padding: 0, height: cardBodyHeight - 10 }}
                >
                    {!remoteOrganizationInfo?.isOpenExamine && !remoteOrganizationInfo?.isOpenApprove && (
                        <div style={{ margin: 10 }}>
                            <Alert message="请联系服务商开启审核审批功能！" type="warning" />
                        </div>
                    )}
                    {remoteOrganizationInfo?.isOpenExamine && state.roles[state.selectedRole]?.type === "审核" && (
                        <>
                            <div style={{ margin: 10 }}>
                                <Alert
                                    message={"审核层级：" + state.roles[state.selectedRole]?.level}
                                    type="info"
                                    action={
                                        <Button size="small" onClick={openSetLevelModal}>
                                            设置层级
                                        </Button>
                                    }
                                />
                            </div>
                            {state.roleGroupMembers.map((item) => (
                                <List
                                    key={item.arLeve}
                                    header={item.arLeve + " 级成员"}
                                    loading={state.memberLoading}
                                    dataSource={item.items}
                                    renderItem={({ member }, index) => {
                                        return (
                                            <List.Item
                                                key={index}
                                                className={`list-item`}
                                                header={<Avatar shape="square" src={<Jdenticon value={member?.omName || "-"} />} />}
                                                main={
                                                    <div>
                                                        <div
                                                            style={{
                                                                color: "var(--semi-color-text-0)",
                                                                fontWeight: 500,
                                                            }}
                                                        >
                                                            {member?.omName || "-"}
                                                        </div>
                                                        {member.omRoge} - {member.omIfim ? "内部成员" : "外部成员"} - {member.omPosi}
                                                    </div>
                                                }
                                                extra={
                                                    <Popconfirm
                                                        placement="topRight"
                                                        title={`确认要从应用角色里移除该成员【${member?.omName}】吗?`}
                                                        onConfirm={() => deleteRoleMember(member.omUuid)}
                                                    >
                                                        <Button theme="borderless" icon={<IconDelete style={{ color: "#E91E63" }} />} />
                                                    </Popconfirm>
                                                }
                                            ></List.Item>
                                        );
                                    }}
                                />
                            ))}
                        </>
                    )}
                    {remoteOrganizationInfo?.isOpenApprove && state.roles[state.selectedRole]?.type === "审批" && (
                        <div style={{ margin: 10 }}>
                            <Alert message="请在组织架构管理设置人员架构，申请人的直属上级即为审批人！" type="info" />
                        </div>
                    )}
                    {(remoteOrganizationInfo?.isOpenExamine || remoteOrganizationInfo?.isOpenApprove) && state.roles[state.selectedRole]?.type === "停用" && (
                        <div style={{ margin: 10 }}>
                            <Alert message="已停用！" type="warning" />
                        </div>
                    )}
                </SemiCard>
            </Col>
        </Row>
    );
}
